package models

import (
	"time"

	"github.com/astaxie/beego/validation"
)

type Role struct {
	Id          int       `gorm:"primaryKey" json:"id" form:"id"`
	Name        string    `valid:"Required;" json:"name" form:"name"` // 不能为空
	Description string    `json:"description" form:"description"`
	GuardName   string    `json:"guardName" form:"guardName"`
	Status      int       `json:"status" form:"status"`
	CreatedAt   time.Time `json:"createdAt" form:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt" form:"updatedAt"`
	DeletedAt   time.Time `json:"deletedAt"`
}
type RoleHasPermission struct {
	PermissionId int `json:"permissionId"`
	RoleId       int `json:"roleId"`
}

func (m *Role) TableName() string {
	return TableName("roles")
}

func (m *Role) RHPTableName() string {
	return TableName("role_has_permissions")
}

// 自定义验证规则
func (m *Role) SelfValid() (msg interface{}) {
	valid := validation.Validation{}
	if b, _ := valid.Valid(m); !b {
		for _, err := range valid.Errors {
			return err.Message
		}
	}
	return nil
}

/**
* @param roleId 角色id
 */
func (m *Role) GetPermissionIdsByRole(roleId int) []*RoleHasPermission {
	list := make([]*RoleHasPermission, 0)
	Db.Debug().Table(m.RHPTableName()).Where("role_id = ?", roleId).Find(&list)
	return list
}
